var express = require('express');
// var mongoose = require('mongoose');
var articleModel = require('../model/articleModel');

var router = express.Router();


// mongoose.connect("mongodb://localhost/myBlog");
// var db = mongoose.connection;

var mongoose = require('mongoose');
mongoose.connection.openUri('mongodb://localhost/myBlog');


// router.use('/delete-article', function (req, res, next) {
//     var param = req.query;
//
//     console.log('param: '+param);
//
//     // res.send(param);
//     res.write('success');
//
//     next();
// });


// router.use('/delete-article', require('./update-article'));





router.get('/article', function (req, res) {
    var PageLimit = 5;
    var SumCount = 0;
    var curentPage = 1;

    if (req.query.page) {
        curentPage = req.query.page;
    }

    if (req.query.limit) {
        PageLimit = req.query.limit;
    }

    articleModel.count().then(function (count) {
        SumCount = count;
        console.log('count: '+count);
    }).then(function () {
        articleModel.find(function (err, articles) {
            if (err) {
                console.log('fail');
                res.json(err);
            } else {
                console.log('success');

                var pageCount = 0;
                if (SumCount%PageLimit == 0) {
                    pageCount = parseInt(SumCount/PageLimit);
                } else {
                    pageCount = parseInt(SumCount/PageLimit + 1);
                }

                var passValue = {
                    articles: articles,
                    pageCount: pageCount,
                    curentPage: curentPage,
                    SumCount: SumCount
                };

                res.render('article', passValue);
            }
        }).sort({time:-1}).skip((curentPage-1)*PageLimit).limit(PageLimit);
    });
});

router.use('/update-article', require('./update-article'));


router.delete('/delete-article', function (req, res) {
    var param = req.body;

    console.log('query: '+JSON.stringify(req.query));
    console.log('body: '+JSON.stringify(req.body));

    // res.send('delete-article');

    var articleID = param.articleID;


    articleModel.findByIdAndRemove({_id: articleID}, function (error) {
        if (!error) {
            console.log('delete ok');
            // res.redirect('/article');
            res.send('success');
        } else {
            console.log(error);
            res.send(error);
        }
    });
});



module.exports = router;
